package com.leetcode.search;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * date:
 * description:
 */
public class RotationDependency {

    public static int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> edges = new ArrayList<>();
        int[] indeg = new int[numCourses];
        Deque<Integer> queue = new LinkedList<>();
        int[] res = new int[numCourses];
        for (int i = 0; i < numCourses; i++){
            edges.add(new ArrayList<>());
        }
        for(int[] prerequisite : prerequisites){
            edges.get(prerequisite[1]).add(prerequisite[0]);
            indeg[prerequisite[0]]++;
        }
        for(int i = 0; i < numCourses; i++){
            if(indeg[i] == 0){
                queue.offer(i);
            }
        }
        int index = 0;
        while(!queue.isEmpty()){
            int course = queue.poll();
            res[index++] = course;
            for(int i : edges.get(course)){
                indeg[i]--;
                if(indeg[i] == 0){
                    queue.offer(i);
                }
            }
        }
        if(index == numCourses){
            return res;
        }else{
            return new int[0];
        }
    }
}
